import Vue from 'vue'
import VueRouter from 'vue-router'

import Layout from '@/views/layout'
import Home from '@/views/layout/home.vue'
import Category from '@/views/layout/category.vue'
import Cart from '@/views/layout/cart.vue'
import User from '@/views/layout/user.vue'
import store from '@/store'

// 懒加载，注意改为异步，import放到后面
const Login = () => import('@/views/login')
const Search = () => import('@/views/search')
const SearchList = () => import('@/views/search/list')
const ProDetail = () => import('@/views/prodetail')
const Pay = () => import('@/views/pay')
const MyOrder = () => import('@/views/myorder')
const Address = () => import('@/views/address')
const AddressEdit = () => import('@/views/address/edit')
const UserRegister = () => import('@/views/register')
const AiChat = () => import('@/views/ai/index.vue')
const MedicalRecord = () => import('@/views/medicalRecord/index.vue')
Vue.use(VueRouter)

const routes = [
  { path: '/login', component: Login },
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      { path: '/home', component: Home },
      { path: '/category', component: Category },
      { path: '/aichat', component: AiChat },
      { path: '/cart', component: Cart },
      { path: '/user', component: User }
    ]
  },
  { path: '/addressedit/:index', component: AddressEdit },
  { path: '/addressedit', alias: '/addressedit/', component: AddressEdit },
  { path: '/search', component: Search },
  { path: '/searchlist', component: SearchList },
  // 动态路由传参，确认将来是哪个商品，路由参数中携带id
  { path: '/prodetail/:id', component: ProDetail },
  { path: '/pay', component: Pay },
  { path: '/myorder', component: MyOrder },
  { path: '/address', component: Address },
  { path: '/register', component: UserRegister },
  { path: '/medicalrecord', component: MedicalRecord }
]

const router = new VueRouter({
  routes
})

// 全局导航守卫
// 所有的路由在真正被访问到之前（解析渲染对应组件页面前），都会先经过全局前置守卫
// 只有全局前置守卫放行了，才会到达对应的页面
// to:到哪里去，到哪去的完整路由信息对象（路径，参数）
// from：从哪里来，从哪来的完整路由信息对象（路径，参数）
// next（)：是否放行
// （1）next（)直接放行，放行到to要去的路径
// （2）next（路径）进行拦截，拦截到next里面配置的路径

/// 定义一个数组，专门用户存放所有需要权限访问的页面
const authUrls = ['/pay', '/myorder']
router.beforeEach(async (to, from, next) => {
  // 默认不放行，next()可所有通过
  if (!authUrls.includes(to.path)) {
    next()
    return
  }

  // 权限网页，判断token
  const token = await await store.dispatch('checkLoginStatus') // 使用导入的 store
  if (token) {
    next()
  } else {
    next('/login')
  }
})

export default router
